<template>
  <div class="sys-section-bg">
    <div style="height:32px;"></div>
    <el-row :gutter="20" class="sys-stat-row">
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#409EFF" size="22"><i-ep-folder /></el-icon>
            <div class="stat-info">
              <div class="stat-title">文件总数</div>
              <div class="stat-value">{{ files.length }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#67C23A" size="22"><i-ep-folder /></el-icon>
            <div class="stat-info">
              <div class="stat-title">文档文件</div>
              <div class="stat-value">{{files.filter(f => ['pdf', 'doc', 'docx', 'txt', 'rtf'].includes(f.fileExtension)).length}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#E6A23C" size="22"><i-ep-folder /></el-icon>
            <div class="stat-info">
              <div class="stat-title">图片文件</div>
              <div class="stat-value">{{files.filter(f => ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(f.fileExtension)).length}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#F56C6C" size="22"><i-ep-folder /></el-icon>
            <div class="stat-info">
              <div class="stat-title">其他文件</div>
              <div class="stat-value">{{files.filter(f => !['pdf', 'doc', 'docx', 'txt', 'rtf', 'jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(f.fileExtension)).length}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-divider content-position="left">文件列表</el-divider>
    <div class="page-title">
      <el-icon><i-ep-folder /></el-icon>
      <span style="margin-left: 8px; font-size: 20px; font-weight: bold;">文件管理</span>
    </div>
    <div class="toolbar">
      <el-input v-model="fileSearch" placeholder="请输入文件名/类型" style="width: 240px; margin-right: 16px;" clearable />
      <el-button type="primary" @click="handleFileSearch">搜索</el-button>
      <el-button type="success" @click="openAddFileDialog" style="margin-left: 16px;">上传文件</el-button>
    </div>
    <el-table :data="pagedFiles" style="width: 100%; margin-top: 16px;" v-loading="fileLoading">
      <el-table-column prop="fileName" label="文件名" />
      <el-table-column prop="fileExtension" label="类型" />
      <el-table-column label="大小">
        <template #default="{ row }">
          {{ formatFileSize(row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" />
      <el-table-column label="创建时间">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="downloadFile(row)">下载</el-button>
          <el-button size="small" type="danger" @click="handleDeleteFile(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="total, prev, pager, next, jumper" :total="filteredFiles.length" :page-size="filePageSize" :current-page="fileCurrentPage" @current-change="handleFilePageChange" style="margin-top: 16px; text-align: right;" />
    
    <!-- 上传文件弹窗 -->
    <el-dialog title="上传文件" v-model="fileDialogVisible" width="400px" @close="resetFileDialog">
      <el-form :model="fileDialogForm" :rules="fileDialogRules" ref="fileDialogFormRef" label-width="80px">
        <el-form-item label="文件" prop="file">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="fileDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFileDialog">上传</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getApiUrl } from '../config/api.js'

// 文件管理数据
const files = ref([])
const fileSearch = ref('')
const filePageSize = ref(10)
const fileCurrentPage = ref(1)
const fileDialogVisible = ref(false)
const fileDialogForm = ref({ file: null })
const fileDialogFormRef = ref(null)
const fileLoading = ref(false)
const fileList = ref([])
const fileDialogRules = {
  file: [{ required: true, message: '请选择文件', trigger: 'change' }]
}

const filteredFiles = computed(() => {
  return files.value
})

const pagedFiles = computed(() => {
  const start = (fileCurrentPage.value - 1) * filePageSize.value
  return filteredFiles.value.slice(start, start + filePageSize.value)
})

// 获取文件列表
const fetchFiles = async () => {
  try {
    const res = await axios.get(getApiUrl('/file/list'))
    
    if (res.data) {
      files.value = res.data
    }
  } catch (error) {
    console.error('获取文件列表失败:', error)
    ElMessage.error('获取文件列表失败')
  }
}

// 搜索文件
const searchFiles = async () => {
  try {
    const searchData = {
      keyword: fileSearch.value,
      fileType: null, // No specific file type filtering in this component
      dateRange: null // No date range filtering in this component
    }
    
    const res = await axios.post(getApiUrl('/file/search'), searchData)
    
    if (res.data) {
      files.value = res.data
    }
  } catch (error) {
    console.error('搜索文件失败:', error)
    ElMessage.error('搜索文件失败')
  }
}

// 上传文件
const uploadFile = async (file) => {
  try {
    const uploadData = new FormData()
    uploadData.append('file', file)
    uploadData.append('folderId', null) // No folder selection in this component
    
    const res = await axios.post(getApiUrl('/file/upload'), uploadData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (res.data.success) {
      ElMessage.success('文件上传成功')
      fetchFiles()
    } else {
      ElMessage.error(res.data.message || '上传失败')
    }
  } catch (error) {
    console.error('上传文件失败:', error)
    ElMessage.error('上传文件失败')
  }
}

// 删除文件
const deleteFile = async (fileId) => {
  try {
    const res = await axios.delete(getApiUrl(`/file/delete/${fileId}`))
    
    if (res.data.success) {
      ElMessage.success('文件删除成功')
      fetchFiles()
    } else {
      ElMessage.error(res.data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除文件失败:', error)
    ElMessage.error('删除文件失败')
  }
}

// 下载文件
const downloadFile = async (file) => {
  try {
    const res = await axios.get(getApiUrl(`/file/download/${file.id}`), {
      responseType: 'blob'
    })
    
    if (res.status === 200) {
      const url = window.URL.createObjectURL(new Blob([res.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', file.fileName)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      ElMessage.success('文件下载成功')
    }
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败')
  }
}

function handleFileSearch() {
  if (fileSearch.value.trim()) {
    searchFiles()
  } else {
    fetchFiles()
  }
  fileCurrentPage.value = 1
}

function openAddFileDialog() {
  fileDialogVisible.value = true
  fileList.value = []
  nextTick(() => fileDialogFormRef.value && fileDialogFormRef.value.clearValidate())
}

function resetFileDialog() {
  fileDialogForm.value = { file: null }
  fileList.value = []
}

function handleFileChange(file) {
  fileDialogForm.value.file = file.raw
}

async function submitFileDialog() {
  fileDialogFormRef.value.validate(async valid => {
    if (!valid) return
    if (fileDialogForm.value.file) {
      const uploadedFile = await uploadFile(fileDialogForm.value.file)
      if (uploadedFile) {
        fileDialogVisible.value = false
      }
    }
  })
}

function handleDeleteFile(row) {
  ElMessageBox.confirm(`确定要删除文件 ${row.fileName} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteFile(row.id)
  })
}

function handleFilePageChange(page) {
  fileCurrentPage.value = page
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '--'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchFiles()
})
</script>

<style scoped>
.sys-section-bg {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.sys-stat-row {
  margin-bottom: 24px;
}

.sys-stat-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.sys-stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 16px;
}

.stat-info {
  margin-left: 16px;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.page-title {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  color: #333;
}

.toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.upload-demo {
  width: 100%;
}
</style> 